package com.chookss.mine.personal.collection;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.liulishuo.okdownload.DownloadTask;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class CollectionDocumentFragment extends CollectionBaseFragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.llBg)
    LinearLayout llBg;

    private View emptyView;
    private TextView tvNone;//空布局;
    private ImageView ivEmpty;//空布局;
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private CollectionAdapter adapter;
    private List<DocunmentEntity> list = new ArrayList<>();
    private boolean isManage = false;//是否是管理模式
    private String UPLOADTAG = "CollectionDocumentFragment_DownloadFile";//下载文件打的标签

    public CollectionDocumentFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.common_srlview_center_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        registerBoradcastReceiver();
        return view;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        rv.setBackgroundColor(getResources().getColor(R.color.white));
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new CollectionAdapter(R.layout.item_collection_document, getActivity(), list);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_empty, rv, false);
        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
        layoutParams.height = Utils.getScreenHeight(mContext) - Utils.dip2px(mContext, (float) 100.5);
        emptyView.setLayoutParams(layoutParams);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无资料收藏");
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        srlView.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize);
        String url = Urls.getMyItemByType;
        map.put("messageType", "3");// 3:资料库 4：图库 5：图文
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<DocunmentEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<DocunmentEntity>>() {
            @Override
            public void onSuccess(List<DocunmentEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    }
                }
                setSize(list.size());
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }

    class CollectionAdapter extends BaseQuickAdapter<DocunmentEntity, BaseViewHolderEx> {
        private Context context;

        public CollectionAdapter(int layoutResId, Context context, @Nullable List<DocunmentEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, DocunmentEntity item) {

            RelativeLayout rlChoice = helper.getView(R.id.rlChoice);
            ImageView item_choice = helper.getView(R.id.item_choice);
            ImageView ivIconType = helper.getView(R.id.ivIconType);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvItemSize = helper.getView(R.id.tvItemSize);
            TextView tvName = helper.getView(R.id.tvItemName);
            ProgressBar progressBar = helper.getView(R.id.progressBar);

            if (isManage) {
                rlChoice.setVisibility(View.VISIBLE);
                if (item.isChoice()) {
                    item_choice.setBackgroundResource(R.drawable.icon_fx_select);
                } else {
                    item_choice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                }
            } else {
                rlChoice.setVisibility(View.GONE);
            }
            if (item.getProgress() == 0 || item.getProgress() == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(item.getProgress());
            }
            String fileType = item.getFileType();//文件类型1--word 2 --excel 3--PPT  4pdf
            if ("1".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_w_80).into(ivIconType);
            } else if ("2".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_x_80).into(ivIconType);
            } else if ("3".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_p_80).into(ivIconType);
            } else if ("4".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_pdf_80).into(ivIconType);
            } else {
                Glide.with(context).load(R.drawable.icon_mr_80).into(ivIconType);
            }
            tvTitle.setText(item.getDataTitle());
            if (Utils.isNull(item.getCreateTime())) {
                tvItemSize.setText(Utils.changeKM(item.getDataSize()));
            } else {
                tvItemSize.setText(Utils.getAccurateDate(item.getCreateTime()) + "  " + Utils.changeKM(item.getDataSize()));
            }
            tvName.setText("提供人：" + item.getUploadPersonName());
            rlChoice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isChoice()) {
                        item.setChoice(false);
                        item_choice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                        EventBus.getDefault().post(new MyEvent("Collection_Subtract"));
                    } else {
                        item.setChoice(true);
                        item_choice.setBackgroundResource(R.drawable.icon_fx_select);
                        EventBus.getDefault().post(new MyEvent("Collection_Add"));
                    }
                }
            });

            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    requestSTORAGE(item, tvTitle.getText().toString(), helper.getItemPosition());
                }
            });

        }
    }

    private void requestSTORAGE(DocunmentEntity entity, String retitle, int rePosition) {
        XXPermissions.with(mContext)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(entity, retitle, rePosition);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(mContext, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(DocunmentEntity entity, String docTitle, int docPosition) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", entity.getDataCode());
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition, entity.isError());
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void openFile(DocunmentEntity entity, String title, int position, boolean isError) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title) || !MyApp.mIsInitTBSSuccess || isError) {
                if (!MyApp.docunmentOpen) {
                    Intent intent = new Intent(mContext, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    mContext.startActivity(intent);
                }
            } else {
                entity.setProgress(1);
                adapter.notifyItemChanged(position);
                Intent intent = new Intent(mContext, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", UPLOADTAG);
                mContext.startService(intent);
            }

        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
        } else if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("DocumentPreview_error")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(map.get("DocumentPreview_error"))) {
                        list.get(i).setError(true);
                    }
                }

            }
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("documentRefresh")) {
                    srlView.autoRefresh();
                } else if (msg.equals("Collection_Edit")) {
                    isManage = true;
                    adapter.notifyDataSetChanged();
                } else if (msg.equals("Collection_Save")) {
                    isManage = false;
                    adapter.notifyDataSetChanged();
                } else if (msg.equals("Collection_Delete")) {
                    String collectId = "";
                    int index = 0;
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).isChoice()) {
                            if (Utils.isNull(collectId)) {
                                collectId = list.get(i).getDataCode();
                            } else {
                                collectId = collectId + "," + list.get(i).getDataCode();
                            }
                            index = i;
                        }
                    }
                    collectVedio(collectId, index);
                }
            }
        }
    }

    private void collectVedio(String collectId, int index) {
        if (Utils.isNull(collectId)) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("collectId", collectId);
        map.put("collectStatus", "0");
        map.put("collectType", "3"); // 3:资料库 4：图库 5：图文
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.toCollect, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (srlView != null) {
                    if (collectId.contains(",")) {
                        srlView.autoRefresh();
                    } else {
                        list.remove(index);
                        adapter.notifyItemRemoved(index);
                        adapter.notifyItemRangeChanged(index, list.size() - index);
                        if (list.size() == 0) {
                            isEnd = true;
                            adapter.setEmptyView(emptyView);
                        }
                        setSize(list.size());
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!list.get(i).isOpen()) {
                            if (encryptStatus) {
                                list.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }

                    }
                }
            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                mContext.startActivity(newIntent);
            }
        } else {
            if (position < 0) {
                return;
            }
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    list.get(position).setProgress(percent);
                    adapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    list.get(position).setProgress(100);
                    adapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, UPLOADTAG);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(UPLOADTAG);// 获取数据
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        if (unbinder != null) {
            unbinder.unbind();
        }
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        }
    }

    @Override
    public void initImmersionBar() {

    }
}
